/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.pbs.batch;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import org.apache.log4j.Logger;


public class PBSBatch {

        /*
         * Ekasit increased RECEIVE_BUFFER_SIZE from 4096 to 40960
         */
	private static final int RECEIVE_BUF_SIZE = 40960;
	private static final String STREAM_CHARSET = "US-ASCII";

	protected static final Logger logger = Logger.getLogger(PBSBatch.class);
	protected final DISEncoder encoder = new DISEncoder();
	protected final DISDecoder decoder = new DISDecoder();

	protected void sendData(Socket socket, String data) throws IOException {

		BufferedWriter writer = new BufferedWriter(
				new OutputStreamWriter(socket.getOutputStream(), STREAM_CHARSET));
		writer.write(data);
		writer.flush();
		logger.debug("Sended: " + data);

	}

	protected String receiveData(Socket socket) throws IOException {

		StringBuffer data = new StringBuffer();
		BufferedReader reader = new BufferedReader(
			new InputStreamReader(socket.getInputStream(), STREAM_CHARSET));
		char[] buffer = new char[RECEIVE_BUF_SIZE];

		while(true) {
			int recvLen = reader.read(buffer, 0, buffer.length);
                        /*
                         * Ekasit corrected the EOF condition from <= to < 0
                         */
			if (recvLen < 0)  // 
				break;
			data.append(new String(buffer, 0, recvLen));
                        /*
                         * Ekasit warns this is wrong condition for message
                         *   end.
                         */
			if (recvLen < buffer.length)
				break;
		}

		logger.debug("Received: " + data);
		return data.toString();
	}

}
